package com.kzw.oa.service.ext;

import java.util.Date;

import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kzw.core.Constants;
import com.kzw.core.service.hibernate.DefaultEntityManager;
import com.kzw.oa.comm.service.LogService;
import com.kzw.oa.model.system.AppUser;
import com.kzw.oa.model.system.SystemLog;
import com.kzw.oa.service.system.SystemLogService;

@Service("userDetailsService")
public class AppUserDetailsService extends DefaultEntityManager<AppUser, Long>
		implements UserDetailsService {
	
	@Autowired
	private LogService logService;
	@Autowired
	private SystemLogService systemLogService;

	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {

		String hql = "from AppUser where username=? and delFlag=?";
		AppUser user = getEntityDao().findUnique(hql, username, Constants.FLAG_UNDELETED);

		if (user != null) {
			Hibernate.initialize(user.getRoles());
			Hibernate.initialize(user.getDepartment());
			user.init();
		}
		
		// 登陆日志
		logService.login(user);
		
		// 记录登陆日志信息
		SystemLog log = new SystemLog();
		log.setUserId(user.getUserId());
		log.setUsername(user.getUsername());
		log.setBoard("执法监督");
		log.setExeOperation("登陆系统");
		log.setCreatetime(new Date());
		systemLogService.save(log);
		
		return user;
	}

}
